package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: JW
 * @Description: TODO
 * @DateTime: 2022-02-16 19:12
 **/
@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {


    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private KafkaTemplate kafkaTemplate;


    /**
     * @param apArticle
     * @param content
     * @Author: JW
     * @Description: TODO 生成静态页
     * @Date: 19:12 2022-02-16
     * @Param: [apArticle, content]
     * @return: void
     */
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {

        /*//参数校验
        if (StringUtils.isNotBlank(content)){

            StringWriter out = new StringWriter();
            try {
                //获取模板
                Template template = configuration.getTemplate("article.ftl");
                //构建数据模型
                Map<String,Object> contentDataModel = new HashMap<>();
                contentDataModel.put("content", JSONArray.parseArray(content));
                //合成

                template.process(contentDataModel,out);

            } catch (Exception e) {
                e.printStackTrace();
            }

            //将文件上传到minion中
            InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
            String htmlUrl = fileStorageService.uploadImgFile("", apArticle.getId() + ".html", inputStream);

            //修改加入静态页
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId,apArticle.getId())
                    .set(ApArticle::getStaticUrl,htmlUrl));
        }*/
        //已知文章的id
        //4.1 获取文章内容
        if(StringUtils.isNotBlank(content)) {
            //4.2 文章内容通过freemarker生成html文件
            Template template = null;
            StringWriter out = new StringWriter();
            try {
                template = configuration.getTemplate("article.ftl");
                //数据模型
                Map<String, Object> contentDataModel = new HashMap<>();
                contentDataModel.put("content", JSONArray.parseArray(content));
                //合成
                template.process(contentDataModel, out);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //4.3 把html文件上传到minio中
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", in);


            //4.4 修改ap_article表，保存static_url字段
            apArticleService.update(Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId, apArticle.getId())
                    .set(ApArticle::getStaticUrl, path));

            sendToES(apArticle, content, path);
        }
    }


    /**
     * @Author: JW
     * @Description:  TODO 发送消息给es
     * @Date: 11:37 2022-02-18
     * @Param: [apArticle, content, path]
     * @return: void
    **/
    private void sendToES(ApArticle apArticle, String content, String path) {

        //发送数据文章详情和内容
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }
}
